package com.woyou.ui.adapter;

import java.util.List;

import com.citaq.ideliver.R;
import com.woyou.bean.DeliverTime;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SelectTimeAdapter extends BaseAdapter implements OnClickListener{

	private Context context;
	private List<DeliverTime> data;
	DeliverTime checkedDT;

	public SelectTimeAdapter(Context context, List<DeliverTime> data) {
		this.context = context;
		this.data = data;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.item_selecttime_lv, null);
			viewHolder.view = (RelativeLayout) convertView.findViewById(R.id.item_selecttime_view);
			viewHolder.time = (TextView) convertView.findViewById(R.id.item_selecttime_lv_time);
			viewHolder.cb = (CheckBox) convertView.findViewById(R.id.item_selecttime_lv_cb);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		//判断要设置默认选中项
		if(!setDefaultChecked()){
			data.get(0).setChecked(true);
		}
		DeliverTime dt=data.get(position);
		if(dt.isChecked()){
			checkedDT=data.get(position);
			viewHolder.cb.setChecked(true);
			viewHolder.cb.setBackgroundResource(R.raw.rediobox1);
		}else{
			viewHolder.cb.setChecked(false);
			viewHolder.cb.setBackgroundResource(R.raw.rediobox2);
		}
		
		viewHolder.deliverTime=dt;
		viewHolder.time.setText(data.get(position).getContent());
		viewHolder.cb.setTag(viewHolder);
		viewHolder.view.setTag(viewHolder);
		viewHolder.cb.setOnClickListener(this);
		viewHolder.view.setOnClickListener(this);
		
		return convertView;
	}

	private static class ViewHolder {
		RelativeLayout view;
		TextView time;
		CheckBox cb;
		DeliverTime deliverTime;
	}

	@Override
	public void onClick(View v) {
		ViewHolder viewHolder=(ViewHolder)v.getTag();
		switch(v.getId()){
			case R.id.item_selecttime_lv_cb:
			case R.id.item_selecttime_view:
				for(DeliverTime dt:data){
					dt.setChecked(false);
				}
				viewHolder.deliverTime.setChecked(true);
				checkedDT = viewHolder.deliverTime;
				notifyDataSetChanged();
			break;
		}
	}
	/**
	 * 判断是否有默认选中项
	 */
	public boolean setDefaultChecked(){
		for(DeliverTime dt:data){
			if(dt.isChecked()){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 获取选择的时间
	 * @return
	 */
	public DeliverTime getCheckedDT(){
		return checkedDT;
	}

}
